package cn.yunyichina.openapi.proxy.filter.in.module;

import cn.yunyichina.openapi.proxy.config.HttpServerConfig;
import cn.yunyichina.openapi.proxy.filter.in.InFilter;
import cn.yunyichina.openapi.proxy.filter.in.entity.InRequest;
import cn.yunyichina.openapi.proxy.filter.in.entity.InResponse;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogScene;
import cn.yunyichina.utils.security.AesEncryption;
import cn.yunyichina.utils.security.Base64Method;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by kevin on 2018/3/2.
 */
public class BaseInFilter implements InFilter {
    @Override
    public InResponse doFilter(InRequest inRequest) {
        return null;
    }

    protected InResponse doBaseFilter(InRequest inRequest,String regex) {
        InResponse inResponse=new InResponse(inRequest.getJsonStr());

        Pattern r = Pattern.compile(regex);
        Matcher matcher=r.matcher(inRequest.getJsonStr());
        while (matcher.find()) {
            String matchStr=matcher.group();
            String desStr;
            try {
                String[] strs=matchStr.split("\\|");
                String encryptStr=strs[1];
                desStr= Base64Method.convertSafe64ToBase64(encryptStr);
                desStr= AesEncryption.desencrypt(desStr, HttpServerConfig.getConfig().getAesKey(),
                        HttpServerConfig.getConfig().getAesKey());
                desStr=desStr.trim();
            } catch (Exception e) {
                Log.e(LogScene.PROXY,inRequest.getMethod()+"["+regex+"]解密失败",e);
                return inResponse;
            }

            if(StringUtils.isBlank(desStr)){
                return inResponse;
            }

            inResponse.setJsonStr(inResponse.getJsonStr().replace(matchStr,desStr));
        }

        return inResponse;
    }
}
